package com.lincoln.cloud.servercenter.protocol;

import com.lincoln.cloud.common.bean.ServerMessage;
import com.lincoln.cloud.common.utils.ByteUtil;
import com.lincoln.cloud.common.utils.CommondValue;
import com.lincoln.cloud.servercenter.abstracter.NettyCommunicationProtocol;
import com.lincoln.cloud.servercenter.interfaces.BaseServerInfo;
import com.lincoln.framework.annotation.Execute;
import com.lincoln.framework.annotation.ExecuteTypeEnum;
import com.lincoln.framework.bean.AbstractMsgNoExecute;
import com.lincoln.framework.bean.AbstractMsgNoProtocol;
import com.lincoln.framework.bean.NettyContext;
import com.lincoln.framework.interfaces.BaseProtocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 登陆指令{[no]|登陆|4|[设备号]|[协议号]|[app-name]|[http端口号]|[md5]}
 *
 * @author lincoln
 */
@Execute(deviceType = 1, protocolType = 1, executeType = ExecuteTypeEnum.LOGIN)
public class LoginExecute extends AbstractMsgNoExecute {
    private static final Logger logger = LoggerFactory.getLogger(LoginExecute.class);

    @Override
    public byte[] getServerCmd() {
        return CommondValue.LOGIN_SERVER_CMD.getBytes();
    }

    @Override
    public byte[] getClientCmd() {
        return CommondValue.LOGIN_CLIENT_CMD.getBytes();
    }

    @Override
    public Logger getLogger() {
        return logger;
    }

    @Override
    public boolean decoder(BaseProtocol baseProtocol) {
        BaseServerInfo deviceInfo = NettyContext.getDevice();
        //设备号不为空
        if (deviceInfo.isLogin()) {
            logger.error("同一会话重复登录!");
            return false;
        }
        return true;
    }

    @Override
    public boolean execute(BaseProtocol baseProtocol) {
        ServerMessage serverMessage = NettyCommunicationProtocol.protocol2serverMessage((AbstractMsgNoProtocol) baseProtocol);
        Integer deviceType = (int) ByteUtil.sub(serverMessage.getMsg(), 0, 1)[0];
        Integer protocolType = (int) ByteUtil.sub(serverMessage.getMsg(), 1, 2)[0];
        String name = new String(ByteUtil.sub(serverMessage.getMsg(), 2, serverMessage.getMsg().length - 4));
        Integer httpPort = ByteUtil.byte2int(ByteUtil.sub(serverMessage.getMsg(), serverMessage.getMsg().length - 4, serverMessage.getMsg().length));
        if (null == deviceType || null == protocolType || null == name || null == httpPort) {
            return false;
        }
        return new NettyCommunicationProtocol().login(deviceType, protocolType, name, httpPort);
    }
}
